package com.example.acticity.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangjiapeng
 * @Package com.example.acticity.controller
 * @Description: ${todo}
 * @date 2018/11/30 16:12
 */
@RestController
@RequestMapping("/approval")
@Slf4j
public class ApprovalController {


    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;


    @RequestMapping("/start")
    public String startApproval(){
        try {
            ProcessInstance processInstance = runtimeService.startProcessInstanceById("process:1:7");
            return "流程启动成功，流程id:" + processInstance.getId();
        } catch (Exception e) {
            log.error("",e.getMessage(),e);
        }
        return "流程启动失败";

    }

    @RequestMapping("findTasksByUserId")
    public String findTasksByUserId(String userId) {
        List<Task> resultTask = taskService.createTaskQuery().processDefinitionId("process:1:7").taskCandidateOrAssigned(userId).list();
        List<String> taskIdList = new ArrayList<>();
        for(Task task : resultTask){
            taskIdList.add(task.getId());
        }
        return JSONArray.toJSONString(taskIdList);
    }

    @RequestMapping("/complete")
    public void completeTask(String taskId,String userId,String result) {
        //获取流程实例
        taskService.claim(taskId, userId);

        Map<String,Object> vars = new HashMap<String,Object>();
        vars.put("sign", "true");
        taskService.complete(taskId, vars);
    }


}
